package client

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"todo-demo/model"
)

var db *gorm.DB
var err error

func init() {
	dst := "root:rootroot@(localhost:3306)/todo_demo?charset=utf8mb4&parseTime=True&loc=Local"
	db, err = gorm.Open("mysql", dst)
	if err != nil {
		fmt.Println("Client init catch error =", err)
	}
	fmt.Println("client init success")
}

type MysqlClient struct {
}

func (m MysqlClient) Migrate() {
	fmt.Println("mysqlClient.Migrate")
	result := db.AutoMigrate(&model.Record{})
	fmt.Printf("automigrate result =%#v", result)
	if result.Error != nil {
		fmt.Println("MysqlClient.Migrate model.Record catch error:", result.Error)
	} else {
		fmt.Println("MysqlClient.Migrate model.Record success!")
	}
}

func (m MysqlClient) Add(record *model.Record) error {
	result := db.Create(&record)
	return result.Error
}

func (m MysqlClient) LoadRecord(recordList *[]model.Record) {
	db.Find(&recordList, &model.Record{}).Where("state = 0")

}

func (m MysqlClient) Finish(recordId string) {

	db.Where("id=?", recordId).Delete(&model.Record{})

}
